package com.zmn.oms.task.listener;

import com.alibaba.fastjson.JSON;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.manager.mq.annotation.AliyunMQHandler;
import com.zmn.manager.mq.annotation.AliyunMQListener;
import com.zmn.oms.business.interfaces.log.OrderLogBService;
import com.zmn.oms.common.constant.MessageQueueTagConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.dto.OmsOperator;
import com.zmn.oms.common.dto.OrderLogAddDTO;
import com.zmn.oms.model.entity.log.OrderLog;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.aop.OrderWorkLogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 类描述: 工单日志监听类
 *
 * @author: liudi
 * @since: 2022/02/24 16:14
 */
@Slf4j
@AliyunMQListener(topic = "${spring.mq.topic.oms}")
@Component
public class OrderWorkLogListener {

	@Resource
	private OrderLogBService orderLogBService;

	@Resource
	private OrderWorkService orderWorkService;

	/**
	 * 保存日志记录
	 *
	 * @param message
	 * @return
	 * @author liudi
	 * @since: 2022/2/24 17:01
	 */
	@AliyunMQHandler(tags = MessageQueueTagConsts.ORDER_LOG)
	public void saveLogRecord(String message) {
		log.info("保存工单日志记录 入参：[{}]", message);
		try {
			OrderLogAddDTO addDTO = JSON.parseObject(message, OrderLogAddDTO.class);

			OrderWork orderWork = orderWorkService.findOrderWorkByKey(addDTO.getOrderId(), addDTO.getWorkId());
			OmsOperator operator = BeanMapper.map(addDTO, OmsOperator.class);
			OrderLog orderLog = BeanMapper.map(addDTO, OrderLog.class);

			orderLog.setTypeName(OrderLogConsts.getOrderLogTypeName(orderLog.getType()));
			orderLog.setOperatorTypeName(GlobalConsts.getOperatorTypeName(addDTO.getOperatorType()));
			orderLog.setCreateTime(DateUtil.getNow());

			OrderWorkLogUtils.processOrderLogOperater(orderLog, operator);
			OrderWorkLogUtils.processOrderLogStatus(orderLog, orderWork, operator);

			orderLogBService.save(orderLog);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("保存工单日志失败 入参：{} ，异常：{}", message, e);
		}
	}

}